angular.module('moti.controllers.orderslist', ['moti.services.regionsService', 'moti.services.ordersService', 'moti.directive.modal'])
    .controller('ordersListCtrl', ['$scope', 'RegionsInterface', 'OrdersInterface', '$modal', function($scope, RegionsInterface, OrdersInterface, $modal){

        //获取景区列表
        RegionsInterface.getRegionsList().then(function(data){
            $scope.regions = data;
        });

        //下拉框数据
        $scope.order_status_options = [{
            "value": 0,
            "label": "待支付"
        },{
            "value": 1,
            "label": "支付中"
        },{
            "value": 2,
            "label": "待出票"
        },{
            "value": 3,
            "label": "已出票"
        },{
            "value": 4,
            "label": "已出行"
        },{
            "value": 5,
            "label": "已取消"
        },{
            "value": 6,
            "label": "退款中"
        },{
            "value": 7,
            "label": "退款成功"
        }];
        $scope.visitor_type_options = [{
            "value": 0,
            "label": "散客"
        },{
            "value": 1,
            "label": "团体"
        }];
        $scope.order_type_options = [{
            "value": 0,
            "label": "普通"
        },{
            "value": 1,
            "label": "散拼"
        }];
        $scope.is_group_options = [{
            "value": 1,
            "label": "已成团"
        },{
            "value": 0,
            "label": "未成团"
        }];

        //搜索条件
        $scope.search_obj = {
            "from_date" : moment().subtract(1, 'month').toISOString(),
            "to_date" : moment().toISOString(),
            "visitor_name" : "",
            "mobile" : "",
            "order_id" : "",
            "order_type" : "",
            "is_group" : "",
            "region_id" : "",
            "limit" : 30,//每页显示条数
            "offset" : 0//跳过的个数
        };

        //搜索事件 type:0-不是分页 1-分页
        $scope.searchOrder = function(type, page){
            //分页的时候不是当前页才触发
            if(type == 0 || (type == 1 && page != $scope.page_cur)){
                $scope.isLoading = true;
                //不是分页：重置offset
                if(type == 0){
                    $scope.search_obj.offset = 0;
                }
                //分页：计算offset
                if(type == 1){
                    $scope.page_cur = page;
                    $scope.search_obj.offset = (page - 1) * $scope.search_obj.limit;
                }
                //搜索接口
                OrdersInterface.getOrders($scope.search_obj).then(function(data){
                    $scope.orders = data;
                    angular.forEach($scope.orders.items, function(value, key) {
                        value.create_time = moment(value.create_time).format('YYYY-MM-DD');
                        value.is_group_desc = value.is_group == true ? "已成团" : "未成团";
                        value.isTicket = value.operate.indexOf("ticket") != -1;
                    });
                    //计算页数
                    if(type == 0){
                        $scope.pages = [];
                        $scope.page_cur = 1;
                        var page_count = Math.ceil(data.total / $scope.search_obj.limit);
                        for(var i = 1; i <= page_count; i++){
                            $scope.pages.push(i);
                        }
                    }
                    $scope.isLoading = false;
                });
            }
        };
        $scope.searchOrder(0);

        //导出表格
        function downloadFile(fileName, content){
            var aLink = document.createElement('a');
            var blob = new Blob([content]);
            var evt = document.createEvent("HTMLEvents");
            evt.initEvent("click", false, false);
            aLink.download = fileName;
            aLink.href = URL.createObjectURL(blob);
            aLink.dispatchEvent(evt);
        }
        $scope.export = function(){
            $scope.export_obj = angular.copy($scope.search_obj);
            delete $scope.export_obj.limit;
            delete $scope.export_obj.offset;
            OrdersInterface.export($scope.export_obj).then(function(data){
                downloadFile("orders.csv", data);
            });
        };

        //出票
        var ticket_modal;
        $scope.getTicket = function(order){
            $scope.cur_orderId = order.order_id;
            OrdersInterface.getBatchInfo($scope.cur_orderId).then(function(data){
                ticket_modal = $modal({
                    id : 'ticket-modal',
                    text : '您是否要出票当前线路下的所有订单？<br />已出票访客人数：' + data.hasTicketVisitorCount + '<br />待出票访客人数：' + data.readyTicketVisitorCount
                });
                ticket_modal.show();
            });
        };
        $("#ticket-btn").off("click").on("click", function(){
            OrdersInterface.addTicket($scope.cur_orderId, {}).then(function(data){
                ticket_modal.hide();
                $modal({id : 'tip-modal', text : "正在单张出票中，请稍候查看结果"}).show().autoHide();
                $scope.isLoading = true;
                setTimeout(function(){$scope.searchOrder(0);}, 2000);
            });
        });
        $("#ticket-btn-batch").off("click").on("click", function(){
            OrdersInterface.addTicket($scope.cur_orderId, {is_batch : "1"}).then(function(data){
                ticket_modal.hide();
                $modal({id : 'tip-modal', text : "正在批量出票中，请稍候查看结果"}).show().autoHide();
                $scope.isLoading = true;
                setTimeout(function(){$scope.searchOrder(0);}, 2000);
            });
        });

        //时间选择控件
        $('#time').val(moment().subtract(1, 'month').format('YYYY/MM/DD') + ' - ' + moment().format('YYYY/MM/DD')).daterangepicker({
            startDate : moment().subtract(1, 'month'),
            endDate : moment(),
            locale : {
                applyLabel : '确定',
                cancelLabel : '取消',
                fromLabel : '起始时间',
                toLabel : '结束时间',
                customRangeLabel : '自定义',
                daysOfWeek : [ '日', '一', '二', '三', '四', '五', '六' ],
                monthNames : [ '一月', '二月', '三月', '四月', '五月', '六月',
                    '七月', '八月', '九月', '十月', '十一月', '十二月' ]
            }
        }, function(start, end, label){
            $scope.search_obj.from_date = start.toISOString();
            $scope.search_obj.to_date = end.toISOString();
            //格式化日期显示框
            $('#time').val(start.format('YYYY/MM/DD') + ' - ' + end.format('YYYY/MM/DD'));
        });

    }]);